﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Thingpower.SS.EduOnline.Core
{
    public class Utils
    {

        public static string GetMessageHtml(string message, bool isSuccess)
        {
            return isSuccess
                ? $@"<div class=""alert alert-success"" role=""alert"">{message}</div>"
                : $@"<div class=""alert alert-danger"" role=""alert"">{message}</div>";
        }

        private const string StrKeyWord = @"select|insert|delete|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec master|netlocalgroup administrators|net user|""|'";

        /// <summary>
        /// 检查文本是否包含SQL关键字
        /// </summary>
        /// <param name="content">被检查的字符串</param>
        /// <returns>存在SQL关键字返回true，不存在返回false</returns>
        private static bool CheckKeyWord(string content)
        {
            string word = content;
            string[] patten1 = StrKeyWord.Split('|');
            foreach (string i in patten1)
            {
                if (word.Contains(" " + i) || word.Contains(i + " "))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 检查文本是否注入攻击
        /// </summary>
        /// <param name="content">被检查的字符串</param>
        /// <returns></returns>
        public static bool IsAttack(string content)
        {
            if (String.IsNullOrWhiteSpace(content)) return false;

            //存在单引号且包含SQL命令
            return (content.Contains("'") || CheckKeyWord(content));
        }

        /// <summary>
        /// 移除SQL命令及单引号
        /// </summary>
        /// <param name="content">被检查的字符串</param>
        /// <returns></returns>
        public static string RemoveKeywords(string content)
        {
            if (String.IsNullOrWhiteSpace(content)) return "";

            //替换高危险单引号
            content = content.Replace("'", "");

            string[] patten1 = StrKeyWord.Split('|');
            foreach (string i in patten1)
            {
                content = content.Replace(i, "");
            }

            return content;
        }
    }
}